package cn.sfturing.utils;

import java.util.Properties;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class MailUtil {
    private static final String mailuser = "184364227@qq.com"; // 发件人称号，同邮箱地址
    private static final String mailpassword = "xxxxxxxxxxxx"; // 如果是qq邮箱可以使户端授权码，或者登录密码
    private static Logger log = LoggerFactory.getLogger(MailUtil.class);

    public boolean sendMail(String to, String personal, String title, String content) {
        Properties properties = new Properties();
        // 验证
        properties.put("mail.smtp.auth", "true");
        // 设置邮件服务器
        properties.put("mail.smtp.host", "smtp.qq.com");
        // 发件人的账号
        properties.put("mail.user", mailuser);
        //发件人的密码
        properties.put("mail.password", mailpassword);

        // 构建授权信息，用于进行SMTP进行身份验证
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 用户名、密码
                String userName = properties.getProperty("mail.user");
                String password = properties.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };

        final MimeMessage mailMessage;
        // 使用环境属性和授权信息，创建邮件会话
        Session mailSession = Session.getInstance(properties, authenticator);

        try {
            // 创建邮件消息
            MimeMessage message = new MimeMessage(mailSession);

            // 设置发件人
            String username = properties.getProperty("mail.user");
            InternetAddress form = new InternetAddress(username);
            message.setFrom(form);

            // 设置收件人
            InternetAddress toAddress = new InternetAddress(to);
            message.setRecipient(Message.RecipientType.TO, toAddress);

            // 设置邮件标题
            message.setSubject(title);

            // 设置邮件的内容体
            message.setContent(personal + content, "text/html;charset=UTF-8");

            // 发送邮件
            Transport.send(message);

        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            return false;
        }

        return true;
    }

    // 测试工具类是否可以正常运行
    public static void main(String[] args) {
        MailUtil mu = new MailUtil();
        mu.sendMail("z184364227@163.com", "PRO", "测试", "这是一封测试邮件");
        System.out.println("邮件发送成功");
    }

}
